package com.xyazm.order.statemachine.action.order.create.node;

import com.xyazm.coupon.domain.param.ReleaseUserCouponParam;
import com.xyazm.coupon.domain.param.UseUserCouponParam;
import com.xyazm.order.domain.param.CreateOrderParam;
import com.xyazm.order.mapstruct.OrderApiMapstruct;
import com.xyazm.order.remote.CouponRemote;
import com.xyazm.process.engine.process.ProcessContext;
import com.xyazm.process.engine.process.RollbackProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 锁定优惠券节点，异常可回滚
 * @author xuyou
 * @date 2023年02月02日 21:11
 */
@Slf4j
@Component
public class CreateOrderLockCouponNode extends RollbackProcessor {

    @Autowired
    private CouponRemote couponRemote;

    @Override
    protected void processInternal(ProcessContext context) {
        CreateOrderParam createOrderParam = context.get("createOrderParam");
        if (StringUtils.isBlank(createOrderParam.getCouponId())) {
            // 当前订单没有使用优惠券
            return;
        }
        // 转换 核销优惠券 参数
        UseUserCouponParam useUserCouponParam = OrderApiMapstruct.INSTANCE.convertUseUserCouponParam(createOrderParam);
        // 调用优惠券服务api,核销用户优惠券
        couponRemote.useUserCoupon(useUserCouponParam);
    }

    @Override
    protected void rollback(ProcessContext context) {
        CreateOrderParam createOrderParam = context.get("createOrderParam");
        // 转换 释放优惠券 参数
        ReleaseUserCouponParam releaseUserCouponParam = OrderApiMapstruct.INSTANCE.convertReleaseUserCouponParam(createOrderParam);
        doRollback(releaseUserCouponParam);
    }

    /**
     * 一致性框架只能拦截public方法
     */
    // @ConsistencyTask(id = "rollbackLockCoupon", alertActionBeanName = "tendConsistencyAlerter")
    public void doRollback(ReleaseUserCouponParam releaseUserCouponParam) {
        couponRemote.releaseUserCoupon(releaseUserCouponParam);
    }
}
